package com.gc.ip.demo;

import java.util.Vector;

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.gc.ip.IPType;
import com.gc.ip.JIPAddress;
import com.gc.ip.JIPAddressCellEditor;
import com.gc.ip.JIPAddressCellRenderer;

public class JIPAnyTableBuilder
{
	private boolean hasRenderer = false;
	private boolean hasPrefixLength = false;
	private Vector columnNames = null;
	private Vector<Integer> columnWidths = null;
	private Vector<IPType> columnIPTypes = null;
	
	public JIPAnyTableBuilder()
	{
		reset();
	}
	
	public void reset()
	{
		hasRenderer = false;
		hasPrefixLength = false;
		columnNames = new Vector();
		columnWidths = new Vector<Integer>();
		columnIPTypes = new Vector<IPType>();
	}
	
	public JIPAnyTableBuilder hasRenderer(boolean hasRenderer)
	{
		this.hasRenderer = hasRenderer;
		return this;
	}
	public JIPAnyTableBuilder hasPrefixLength(boolean hasPrefixLength)
	{
		this.hasPrefixLength = hasPrefixLength;
		return this;
	}
	public JIPAnyTableBuilder addColumnName(String columnName)
	{
		this.columnNames.add(columnName);
		return this;
	}
	public JIPAnyTableBuilder addColumnWidth(int width)
	{
		this.columnWidths.add(width);
		return this;
	}
	public JIPAnyTableBuilder addColumnIPType(IPType ipType)
	{
		this.columnIPTypes.add(ipType);
		return this;
	}
	
	public JTable build()
	{
		JTable table = null;
		if(columnNames.size() != columnWidths.size())
		{
			throw new IllegalArgumentException("Different size of Column 'names' and 'widths'");
		}
		if(columnNames.size() != columnIPTypes.size())
		{
			throw new IllegalArgumentException("Different size of Column 'names' and 'iptypes'");
		}

		// Table Model
		DefaultTableModel tableModel = new DefaultTableModel((Vector) null, (Vector) columnNames);

		// Init table
		table = new JTable(tableModel);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		// Columns
		JIPAddressCellEditor cellEditor = null;
		JIPAddressCellRenderer renderer = null;
		TableColumn column = null;
		for(int i = 0, columnCount = table.getColumnCount(); i < columnCount; i++)
		{
			column = table.getColumnModel().getColumn(i);

			if(i < columnCount)
			{
				column.setPreferredWidth(columnWidths.get(i));
			}

			cellEditor = new JIPAddressCellEditor(new JIPAddress(hasPrefixLength,
				columnIPTypes.get(i)));
			column.setCellEditor(cellEditor);

			if(hasRenderer)
			{
				renderer = new JIPAddressCellRenderer(new JIPAddress(hasPrefixLength,
					columnIPTypes.get(i)));
				column.setCellRenderer(renderer);
			}
		}

		table.setRowHeight(28);
		return table;
	}
}
